<template>
	<view>
		<!--  #ifdef  MP || APP-PLUS-->
		<cu-custom bgColor="bg-white" :isBack="false">
			<!-- <block slot="backText">返回</block> -->
			<block slot="content">商品分类</block>
		</cu-custom>
		<!--  #endif -->
		<div class="category">
			<div class="content">
				<view>
					<uni-easyinput class="uni-mt-5" suffixIcon="search" v-model="queryParam" placeholder="请输入要查询的商品" @iconClick="queryItems"></uni-easyinput>
				</view>
				<view class="scroll-panel" id="scroll-panel">
					<view class="list-box">
						<view class="left">
							<scroll-view scroll-y="true" :style="{ 'height':scrollHeight + 'px' }"
								:scroll-into-view="leftIntoView">
								<view style="font-size:16px;line-height: 80rpx;font-weight: bold;" class="item"
									v-for="(item,index) in category" :key="index" :class="{ 'active':index==leftIndex }"
									:id="'left-'+index" :data-index="index" @tap="leftTap">{{item.categoryName}}</view>
							</scroll-view>
						</view>
						<view class="main">
							<scroll-view scroll-y="true" :style="{ 'height':scrollHeight + 'px' }" @scroll="mainScroll"
								:scroll-into-view="scrollInto" scroll-with-animation="true">
								<view class="item main-item" v-for="(item,index) in categoryFilters" :key="index"
									:id="'item-'+index">
									<view class="title">
										<view
											style="font-size: 16px;color:#0081FF;margin-bottom:4rpx;margin-top: 4rpx;">
											{{item.categoryName}}</view>
									</view>
									<view class="goods" v-for="(item2,index2) in item.priceStrategyItems" :key="index2">
										<view class="top">
											<!-- <image :src="item2.img_url" mode="" @click="naviToGoods()"></image> -->
											<view class="flex"
												style="justify-content: space-between;flex-grow: .5;line-height: 60rpx;">
												<view class="name">{{item2.productName}}</view>
											</view>

										</view>
										<view class="flex">
											<view class="money"
												style="text-align: right;line-height: 40rpx;margin-bottom: 4px;font-size: 16px;">
												￥{{parseFloat(item2.price).toFixed(2)}} {{item2.fbaseUnitIdfname}}
											</view>
										</view>
										<view class="flex"
											style="justify-content: space-between;flex-grow: .5;line-height: 40rpx;margin-bottom: 5px;font-size: 12px;">
											<view class="specName">{{item2.specName}} </view>
										</view>
										<view class="flex"
											style="justify-content: space-between;flex-grow: .5;line-height: 40rpx;margin-bottom: 5px;font-size: 12px;margin-right: 3px;">
											<view class="specName">{{item2.specCode}} </view>
										</view>
										
										<view v-if="item2.moq > 0 || item2.moqTimes > 1" class="moq">
											<span v-if="item2.moq > 0">起订量<span class="moq_val">&nbsp;{{ item2.moq }}&nbsp;</span>{{item2.fbaseUnitIdfname}}</span>
											<span v-if="item2.moqTimes > 1">{{ item2.moq > 0? '，': '' }}<span class="moq_val">&nbsp;{{ item2.moqTimes }}&nbsp;</span>的倍数报货</span>
										</view>

										<view class="btns">
											<!-- <view class="opts">
												<iconfont icon="reduce" @click="reduce(item,item2)"></iconfont>
												<span >{{item2.num}}</span>
												<iconfont icon="add" @click="add(item,item2)"></iconfont>
											</view> -->
											<view class="opts">
												<span class="l" @click="reduce(item,item2)" v-if="!item2.stopSell">-</span>
												<input :disabled="item2.stopSell" type="number" v-model.number="item2.num" @blur="setCartValue(item,item2,$event)" />
												<span class="r" @click="add(item,item2)" v-if="!item2.stopSell">+</span>
											</view>
											<button class="func" :class="!item2.num? 'disabled': ''" type="warn" size="mini" style="border-radius:25px"
												@click="cartTo(item2)" v-if="!item2.stopSell" :disabled="!item2.num">加入购物车</button>
											<view class="sell_out" v-else>已售罄</view>
										</view>
									</view>
								</view>
								<view class="fill-last" :style="{ 'height':fillHeight + 'px' }"></view>
							</scroll-view>
						</view>
					</view>
				</view>
			</div>
		</div>
	</view>
</template>

<script>
	const category = require("@/static/mockjs/category.js");
	import {
		toLogin,
		getStorageUserInfo,
		getStorageCartInfo,
		setStorageCartInfo,
		get
	} from "@/server/api.js";

	import {
		getPriceStrategyListApi
	} from "@/server/config.js"
	export default {
		data() {
			return {
				scrollHeight: 0,
				scrollTopSize: 0,
				fillHeight: 0, // 填充高度，用于最后一项低于滚动区域时使用
				category: [],
				categoryFilters: [],
				topArr: [],
				leftIndex: 0,
				scrollInto: '',
				addProductNumber: 0, //加入购物车里的商品数量
				userInfo: null,
				queryParam : ''
			}
		},
		async onShow() {
			let openId = uni.getStorageSync('openid');
			if (openId) {
				await get('/erp/openid/find', {openid:openId}).then(function(res) {
					if (!res.data.records[0]) {
						uni.navigateTo({
							url: "/apiPam/logincommon/main"
						});
					}
				})
			}
			toLogin();
			//getCartItemCounts()
			this.userInfo = getStorageUserInfo();

			/* 等待DOM挂载完成 */
			this.$nextTick(() => {
				/* 在非H5平台，nextTick回调后有概率获取到错误的元素高度，则添加200ms的延迟来减少BUG的产生 */
				setTimeout(() => {
					/* 等待滚动区域初始化完成 */
					this.initScrollView().then(() => {
						/* 获取列表数据，你的代码从此处开始 */
						this.getListData();
					})
				}, 500);
			})
		},
		computed: {
			/* 计算左侧滚动位置定位 */
			leftIntoView() {
				return `left-${this.leftIndex > 3 ? (this.leftIndex-3):0}`;
			}
		},
		mounted() {

		},
		methods: {
			queryItems() {
				if(this.queryParam == '' && this.category.length != this.categoryFilters.length) {
					this.categoryFilters = this.category
				} else {
					this.categoryFilters = this.category
					let newCategory = []
					for (let i = 0; i < this.categoryFilters.length;i++) {
						let categoryName = this.categoryFilters[i].categoryName
						let items = this.categoryFilters[i].priceStrategyItems
						let newItems = items.filter(item => item.productName.includes(this.queryParam));
						if(newItems.length > 0) {
							newCategory.push({
								categoryName: categoryName,
								priceStrategyItems: newItems
							})
						}
					}
					this.categoryFilters = newCategory
				}
			},
			naviToGoods() {
				uni.navigateTo({
					url: "/apiShop/goods/main"
				});
			},
			/* 初始化滚动区域 */
			initScrollView() {
				return new Promise((resolve, reject) => {
					let _this = this;
					let view = uni.createSelectorQuery().select('#scroll-panel');
					view.boundingClientRect(res => {
						this.scrollTopSize = res.top;
						let widowsHeight = uni.getSystemInfo({
							success: function(res) {
								_this.scrollHeight = res.windowHeight - _this.scrollTopSize;
							}
						});
						this.$nextTick(() => {
							resolve();
						})
					}).exec();
				});
			},

			// 商品数量加减
			async countGoodsNumber(index, goodIndex, goods, flag) {
				if (flag) {
					goods.num++;
				} else {
					goods.num--;
					if (goods.num == 0) {
						//删除本项目
						this.listData[index].goodsList.splice(goodIndex, 1)
					}
				}
			},

			/* 获取列表数据 */
			async getListData() {

				let userInfo = getStorageUserInfo();
				let priceStrategy = userInfo.priceStrategy;
				const {
					data
				} = await getPriceStrategyListApi(priceStrategy)

				let list = []
				if (data.status == 400) {
					data.errors.forEach(p => {
						uni.showToast({
							title: p.message, //提示的内容,
							duration: 1000, //延迟时间,
							icon: "none",
							mask: true, //显示透明蒙层，防止触摸穿透,
							success: res => {}
						});
						return
					})

				} else {
					for(let i = 0; i < data.length; i++) {
						let category = data[i]
						let items = []
						for(let j = 0; j < category.priceStrategyItems.length; j++) {
							let item = category.priceStrategyItems[j]
							// if (item.moq) {
							// 	item.num = item.moq
							// }
							// if (!item.stopSell) {
								items.push(item)
							// }
						}
						if (items.length > 0) {
							list.push({
								categoryName: category.categoryName,
								priceStrategyItems: items
							})
						}
					}
				}

				this.category = list
				this.categoryFilters = list
				let cartData = getStorageCartInfo()
				let _ = require('lodash');
				let priceStrategyItems = _.map(list, 'priceStrategyItems').flat();
				if (cartData.length > 0) {
					cartData.forEach(p => {
						let item = _.find(priceStrategyItems, {
							'id': p.id
						});
						if (item) {
							this.$set(item, 'num', p.num)
						}
					})
				}

				this.$nextTick(() => {
					this.getElementTop();
				});

			},
			/* 获取元素顶部信息 */
			getElementTop() {
				new Promise((resolve, reject) => {
					let view = uni.createSelectorQuery().selectAll('.main-item');
					view.boundingClientRect(data => {
						resolve(data);
					}).exec();
				}).then((res) => {
					let topArr = res.map((item) => {
						return item.top - this.scrollTopSize; /* 减去滚动容器距离顶部的距离 */
					});
					this.topArr = topArr;

					/* 获取最后一项的高度，设置填充高度。判断和填充时做了 +-20 的操作，是为了滚动时更好的定位 */
					let last = res[res.length - 1].height;
					if (last - 20 < this.scrollHeight) {
						this.fillHeight = this.scrollHeight - last + 20;
					}
				});
			},
			/* 主区域滚动监听 */
			mainScroll(e) {
				let top = e.detail.scrollTop;
				let index = 0;
				/* 查找当前滚动距离 */
				for (let i = (this.topArr.length - 1); i >= 0; i--) {
					/* 在部分安卓设备上，因手机逻辑分辨率与rpx单位计算不是整数，滚动距离与有误差，增加2px来完善该问题 */
					if ((top + 2) >= this.topArr[i]) {
						index = i;
						break;
					}
				}
				this.leftIndex = (index < 0 ? 0 : index);
			},
			/* 左侧导航点击 */
			leftTap(e) {
				let index = e.currentTarget.dataset.index;
				this.scrollInto = `item-${index}`;
			},
			add(category, product) {
				console.info(product.num)
				// product.num++;
				if (!product.num && product.moq) {
					product.num = product.moq;
				} else {
					product.num = product.num + (product.moqTimes || 1);
				}
			},
			setCartValue(category, product, $event) {
				let num = Number($event.target.value.replace(/\D+|^0+/g, ''))
				if (product.moq && num < product.moq) {
					product.num = product.moq
				} else {
					if (product.moqTimes > 0) {
						let sub = (num - (product.moq || 0)) % product.moqTimes
						if (sub <= 0) {
							product.num = num
						} else {
							product.num = num + (product.moqTimes - sub)
						}
					} else {
						product.num = num
					}
				}
			},
			reduce(category, product) {
				let num = product.num;
				num = num - (product.moqTimes || 1);
				if (num < product.moq || 0) {
					num = 0;
				}
				product.num = num;
			},

			//加入购物车
			cartTo(product) {

				if (product.num < product.moq) {
					uni.showToast({
						icon: "none",
						title: "商品数量不正确"
					});
					return
				}
				uni.showToast({
					title: '购物车加入成功',
					duration: 400
				});
				this.addProductNumber += product.num;
				// uni.setTabBarBadge({
				//   index: 2,
				//   text: `${this.addProductNumber}`
				// })

				let cartInfo = getStorageCartInfo()
				if (cartInfo) {
					let hasItem = false
					cartInfo.forEach(item => {
						if (item.id == product.id) {
							hasItem = true
							item.num = product.num
						}
					})
					if (!hasItem) {
						cartInfo.push(product)
					}
				} else {
					cartInfo = []
					cartInfo.push(product)
				}
				setStorageCartInfo(cartInfo)
			}
		}
	}
</script>


<style lang="scss">
	@import './style';
</style>
